/**
 * Author: grx
 * Description: 用于学习模块"倒计时"的工具类
 */
package com.example.parallelandroid.utils;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class CountdownTimeUtil {

    /*倒计时时长  单位：秒*/
    public static int COUNT;
    /*当前做*/
    private static int CURR_COUNT = 0;
    /*预计结束的时间*/
    private static long TIME_END = 0;
    /*总时长与当前时长之差*/
    public static int DIFFERENT;
    /*计时器*/
    private static Timer countdownTimer;
    /*显示倒计时的textView*/
    private static TextView tvHour;
    private static TextView tvMinute;
    private static TextView tvSecond;

    public static MediaPlayer player;
    public static Vibrator vibrator;

    private static Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what <= 0) {
                if (countdownTimer != null) {
                    countdownTimer.cancel();
                    countdownTimer = null;
                    Log.e("CURR_COUNT", CURR_COUNT + "");
                    if (CURR_COUNT <= 0) { // 倒计时自动结束
                        if (player != null) {
                            player.start(); // 开始或恢复播放
                            Log.e("player", "开始播放");
                            player.setLooping(true); // 循环播放
                        }
                        if (vibrator != null) {
                            // 开启震动
                            long[] pattern = new long[]{1000, 1000};
                            vibrator.vibrate(pattern, 0);
                            Log.e("player", "开始震动");
                        }
                    }
                } else {// 关闭响铃或震动
                    if (player != null) {
                        if (player.isPlaying()) {//判断是否正在播放
                            player.stop(); // 停止播放
                            Log.e("player", "停止播放");
                            player.release(); // 释放与此MediaPlayer关联的资源
                            player = null;
                        }
                    }
                    if (vibrator != null) {
                        // 取消震动
                        vibrator.cancel();
                        vibrator = null;
                        Log.e("player", "取消震动");
                    }
                }
                CountdownTimeUtil.tvHour.setText("00");
                CountdownTimeUtil.tvMinute.setText("00");
                CountdownTimeUtil.tvSecond.setText("00");
                CountdownTimeUtil.tvHour.setEnabled(true);
                CountdownTimeUtil.tvMinute.setEnabled(true);
                CountdownTimeUtil.tvSecond.setEnabled(true);
            } else {
                //倒计时效果展示
                String txtTime = formatSecondTime(msg.what);
                String[] times = txtTime.split(":");
                String hour = times[0];
                String minute = times[1];
                String second = times[2];

                Log.e("时间", hour + " : " + minute + " : " + second);

                tvHour.setText("0" + hour);
                if (Integer.parseInt(minute) < 10) {
                    tvMinute.setText("0" + minute);
                } else {
                    tvMinute.setText(minute);
                }
                if (Integer.parseInt(second) < 10) {
                    tvSecond.setText("0" + second);
                } else {
                    tvSecond.setText(second);
                }
                CountdownTimeUtil.tvHour.setEnabled(true);
                CountdownTimeUtil.tvMinute.setEnabled(true);
                CountdownTimeUtil.tvSecond.setEnabled(true);
            }
            super.handleMessage(msg);
        }
    };

    /**
     * 开始倒计时 (响铃模式下)
     * @param player 播放响铃的类
     * @param isFirst 标识是否是第一次进入
     * @param hour 倒计时时长  单位：小时
     * @param minute 倒计时时长  单位：分钟
     * @param tvHour 显示倒计时的小时
     * @param tvMinute 显示倒计时的分钟
     * @param tvSecond 显示倒计时的秒
     */
    public static void startCountdown(MediaPlayer player, Vibrator vibrator, boolean isFirst, int hour, int minute, int second, TextView tvHour, TextView tvMinute, TextView tvSecond) {
        // 获取响铃类
        CountdownTimeUtil.player = player;
        // 获取震动类Vibrate
        CountdownTimeUtil.vibrator = vibrator;
        COUNT = hour * 60 * 60 + minute * 60 + second; // 倒计时总秒数
        long data = System.currentTimeMillis();
        long time = TIME_END;
        // 第一次进入时，重新赋值
        if (isFirst) {
            CURR_COUNT = COUNT;
            time = data + COUNT * 1000;
            TIME_END = time;
        } else {
            DIFFERENT = ((int) (time - data)) / 1000;
            CURR_COUNT = DIFFERENT;
        }
        //开始倒计时
        CountdownTimeUtil.tvHour = tvHour;
        CountdownTimeUtil.tvMinute = tvMinute;
        CountdownTimeUtil.tvSecond = tvSecond;
        if (countdownTimer == null) {
            countdownTimer = new Timer();
            countdownTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Message msg = new Message();
                    msg.what = CURR_COUNT--;
                    handler.sendMessage(msg);
                }
            }, 0, 1000);
            //第二个参数delay:"0"的意思是:无延迟
            //第三个参数period:"1000"的意思是:每隔多长时间调用一次（单位毫秒）
        }
    }

    /**
     * 开始倒计时 (震动模式下)
     * @param vibrator 震动类
     * @param isFirst 标识是否是第一次进入
     * @param hour 倒计时时长  单位：小时
     * @param minute 倒计时时长  单位：分钟
     * @param tvHour 显示倒计时的小时
     * @param tvMinute 显示倒计时的分钟
     * @param tvSecond 显示倒计时的秒
     */
    public static void startCountdown(Vibrator vibrator, boolean isFirst, int hour, int minute, int second, TextView tvHour, TextView tvMinute, TextView tvSecond) {
        // 获取震动类Vibrate
        CountdownTimeUtil.vibrator = vibrator;
        COUNT = hour * 60 * 60 + minute * 60 + second; // 倒计时总秒数
        long data = System.currentTimeMillis();
        long time = TIME_END;
        // 第一次进入时，重新赋值
        if (isFirst) {
            CURR_COUNT = COUNT;
            time = data + COUNT * 1000;
            TIME_END = time;
        } else {
            int the_difference = ((int) (time - data)) / 1000;
            CURR_COUNT = the_difference;
        }
        //开始倒计时
        CountdownTimeUtil.tvHour = tvHour;
        CountdownTimeUtil.tvMinute = tvMinute;
        CountdownTimeUtil.tvSecond = tvSecond;
        if (countdownTimer == null) {
            countdownTimer = new Timer();
            countdownTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Message msg = new Message();
                    msg.what = CURR_COUNT--;
                    handler.sendMessage(msg);
                }
            }, 0, 1000);
            //第二个参数delay:"0"的意思是:无延迟
            //第三个参数period:"1000"的意思是:每隔多长时间调用一次（单位毫秒）
        }
    }

    /**
     * 结束倒计时
     */
    public static void  stopCountdown() {
        //发送消息，结束倒计时
        Message message = new Message();
        message.what = 0;
        handler.sendMessage(message);
    }



    /**
     * 时间格式化方法
     * @param time 秒数
     * @return
     */
    private static String formatSecondTime(int time) {
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time >= 60) {
            minute = time / 60;   //取整
            second = time % 60;   //取余
        } else {
            second = time;
        }
        if (minute >= 60) {
            hour = minute / 60;
            minute = minute % 60;
        }
        String strtime = hour+":"+minute+":"+second;
        return strtime;
    }

}
